<template>
  <div>
    <div class="search">
      <Row>
        <Col>
          <Card>
            <Row>
              <Form ref="searchForm" :model="searchForm" inline :label-width="140" class="search-form">
                <Form-item label="项目名称" prop="">
                  <Input v-model="searchForm.project_name" style="width: 260px;"/>
                </Form-item>
                <Form-item style="margin-left:-100px;" class="br">
                  <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </Form-item>
              </Form>
            </Row>
            <Row class="operation">
              <Button @click="addProject" type="primary" icon="md-add">添加项目</Button>
              <Button @click="editProject" type="warning" icon="ios-bookmarks-outline" >编辑项目</Button>
              <Button @click="viewProject" type="success" icon="ios-eye" >查看项目</Button>
              <Button @click="viewAttachment" type="error" icon="ios-bookmarks-outline" >附件管理</Button>
              <Dropdown @on-click="handleDropdown">
                <Button>
                  更多操作
                  <Icon type="md-arrow-dropdown" />
                </Button>
                <DropdownMenu slot="list">
                  <DropdownItem name="exportData">导出所选数据</DropdownItem>
                  <DropdownItem name="exportAll">导出全部数据</DropdownItem>
                  <DropdownItem name="changeSure">项目类型转换</DropdownItem>
                </DropdownMenu>
              </Dropdown>
              <Button @click="refresh" icon="refresh">刷新</Button>
            </Row>
            <Row>
              <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
              </Alert>
            </Row>
            <Row>
              <Table
                border
                :loading="loading"
                :columns="columns"
                :data="data"
                sortable="custom"
                @on-selection-change="showSelect"
                ref="table">
              </Table>
              <Table :columns="exportColumns" :data="exportData" ref="exportTable" style="display:none"></Table>
            </Row>
            <Row type="flex" justify="end" class="page">
              <Page
                :current="searchForm.pageNumber"
                :total="total"
                :page-size="searchForm.pageSize"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
                :page-size-opts="[10,20,50]"
                size="small"
                show-total
                show-elevator
                show-sizer
              ></Page>
            </Row>
          </Card>
        </Col>
      </Row>
      <Modal v-model="modalExportAll" title="确认导出" :loading="loadingExport" @on-ok="exportAll">
        <p>您确认要导出全部 {{total}} 条数据？</p>
      </Modal>
      <addEdit :data="form" :type="showType" v-model="addEditVisiable" @on-submit="refresh"/>
      <attachment v-model="attachmentVisiable" :data="attachmentValue"/>
    </div>
  </div>
</template>
<script>
import { getProjectList, updateProject, getAllProject } from '@/api/project';
import util from '@/libs/util';
import addEdit from './addEdit';
import attachment from '../attachment/attachmentManager';
export default {
  name: 'project-manager',
  components: {
    addEdit,
    attachment
  },
  data() {
    return {
      loading: false,
      searchForm: {
        project_name: '',
        pageNumber: 1,
        pageSize: 10
      },
      data: [],
      total: 0,
      selectCount: 0,
      exportData: [],
      selectList: [],
      modalExportAll: false,
      loadingExport: true,
      showType: '',
      addEditVisiable: false,
      attachmentVisiable: false,
      form: {},
      columns: [
        {
          type: "selection",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          title: '项目编号',
          key: 'project_code',
          width: 140
        },
        {
          title: '项目名称',
          key: 'project_name',
          width: 200
        },
        {
          title: '用电性质',
          key: 'char_act',
          width: 160
        },
        {
          title: '容量(KVA)',
          key: 'allow_capacity',
          width: 80
        },
        {
          title: '用户名称',
          key: 'project_owner',
          width: 180
        },
          {
              title: '工程摘要',
              key: 'abstract',
              width: 280
          },
        {
          title: '联系人',
          key: 'contact',
          width: 70
        },
        {
          title: '电话',
          key: 'mobile',
          width: 100
        },
        {
          title: '接洽日期',
          key: 'apply_date',
          width: 90
        },
        {
          title: '接洽人',
          key: 'real_name',
          width: 80
        },
        {
          title: "项目类型",
          key: "is_sure",
          align: "center",
          width: 110,
          render: (h, params) => {
            if (params.row.is_sure == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "正常项目"
                  }
                })
              ]);
            } else {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "error",
                    text: "临时项目"
                  }
                })
              ]);
            }
          },
        }
      ],
      exportColumns: [
        {
          title: '项目编号',
          key: 'project_code',
        },
        {
          title: '项目名称',
          key: 'project_name',
        },
        {
          title: '业主',
          key: 'project_owner',
        },
        {
          title: '项目地址',
          key: 'project_address',
        },
        {
          title: '用电性质',
          key: 'char_act',
        },
        {
          title: '容量(KVA)',
          key: 'allow_capacity',
        },
        {
          title: '台',
          key: 'transformer_number',
        },
        {
          title: '用户名称',
          key: 'project_owner',
        },
        {
            title: '工程摘要',
            key: 'abstract',
        },
        {
          title: '联系人',
          key: 'contact',
        },
        {
          title: '电话',
          key: 'mobile',
        },
        {
          title: '接洽日期',
          key: 'apply_date',
        },
        {
          title: '接洽人',
          key: 'real_name',
          width: 80
        },
      ],
    }
  },
  methods: {
    getProjects() {
      this.loading = true;
      getProjectList(this.searchForm).then(res => {
        if (res.code === 0) {
          this.data = res.data.raws;
          this.total = res.data.count;
        }
      });
      this.loading = false;
    },
    init() {
      this.getProjects();
    },
    handleSearch() {
      this.searchForm.project_name = this.searchForm.project_name.trim();
      if (this.searchForm.project_name.length > 0) {
        this.searchForm.pageNumber = 1;
        this.getProjects();
      }
    },
    handleReset() {
      this.searchForm.project_name = '';
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getProjects();
    },
    refresh() {
      this.getProjects();
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getProjects();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getProjects();
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    addProject() {
      const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      this.form = {};
      this.showType = '1';
      this.addEditVisiable = true;
    },
    editProject() {
      if (this.selectList.length !== 1) {
        this.$Message.error('必须且只能选择一条记录进行编辑操作');
        return;
      }
      const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      // 转换null为""
      let v = this.selectList[0];
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.form = data;
      this.showType = '2';
      this.addEditVisiable = true;
    },
    viewProject() {

    },
    handleDropdown(name) {
      switch(name) {
        case 'changeSure':
          if (this.selectList.length !== 1) {
            this.$Message.error('必须且只能选择一条记录进行编辑操作');
            return;
          }
          const is_sure = this.selectList[0].is_sure == 1 ? 0 : 1;
          const params = {id: this.selectList[0].id, is_sure};
          updateProject(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
              this.getProjects();
            }
          })
          break;
        case 'exportData':
          if (this.selectCount <= 0) {
            this.$Message.warning("您还未选择要导出的数据");
            return;
          }
          this.$Modal.confirm({
            title: "确认导出",
            content: "您确认要导出所选 " + this.selectCount + " 条数据?",
            onOk: () => {
              this.$refs.exportTable.exportCsv({
                filename: "工程项目数据"
              });
            }
          });
          break;
        case 'exportAll':
          this.modalExportAll = true;
          break;
      }
    },
    exportAll() {
      getAllProject().then(res => {
        this.modalExportAll = false;
        if (res.code === 0) {
          this.exportData = res.data.raws;
          setTimeout(() => {
            this.$refs.exportTable.exportCsv({
              filename: "工程项目全部数据"
            });
          }, 1000);
        }
      });
    },
    viewAttachment() {
      if (this.selectList.length !== 1) {
        this.$Message.warning('必须选择一条记录进行操作!');
        return;
      }
      this.attachmentValue = {
        project_id: this.selectList[0].id,
        type: 6,
        showAll: false,
        showUploads: true
      }
      this.attachmentVisiable = true;
    }
  },
  mounted() {
    this.init();
  }
}
</script>
<style lang="less">
  @import "./projectManager.less";
</style>